import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogOut } from "@/api";
import { setToken, removeToken } from "@/utils/token";
const state = {
  code: "",
  token: localStorage.getItem("TOKEN"),
  userInfo: {},
};
const mutations = {
  GETCODE(state, value) {
    state.code = value;
  },
  USERLOGIN(state, value) {
    state.token = value;
  },
  GETUSERINFO(state, value) {
    state.userInfo = value;
  },
  CLEAR(state) {
    state.token = "";
    state.userInfo = {};
    removeToken();
  },
};
const actions = {
  //获取验证码
  async getCode(context, phone) {
    let result = await reqGetCode(phone);
    if (result.code == 200) {
      context.commit("GETCODE", result.data);
      return "ok";
    } else {
      return Promise.reject(new Error("FAIL"));
    }
  },
  async userRegister(context, user) {
    let result = await reqUserRegister(user);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  async userLogin(context, data) {
    let result = await reqUserLogin(data);
    if (result.code == 200) {
      context.commit("USERLOGIN", result.data.token);
      setToken(result.data.token);
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  async getUserInfo(context) {
    let result = await reqUserInfo();
    if (result.code == 200) {
      context.commit("GETUSERINFO", result.data);
      return "OK";
    } else {
      return Promise.reject(new Error("FAIL"));
    }
  },
  async userLogOut(context) {
    let result = await reqLogOut();
    if (result.code == 200) {
      context.commit("CLEAR");
      return "OK";
    } else {
      return Promise.reject(new Error("FAIL"));
    }
  },
};
const getters = {};
export default {
  state,
  mutations,
  actions,
  getters,
};
